package com.woniu.woniu_bx.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.pojo.Role;
import com.woniu.woniu_bx.service.RoleService;
import com.woniu.woniu_bx.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

/**
 * @author:GuoHai
 * @program: IntelliJ IDEA
 * @data: 2022/8/29 11:09
 */
@Slf4j
@RestController
@RequestMapping("/admin/role")
public class RoleController {
    @Resource
    private RoleService roleService;

    /**
     * RoleVo包括role，permsId数组，menusId数组
     *
     * @param roleVo
     * @return
     */
    @PostMapping("/addRole")
    @PreAuthorize("hasAnyAuthority('role:add')")
    public ResponseEntity addRole(@RequestBody RoleVo roleVo) {
        log.debug("接收到的参数为：{}", roleVo);
        roleService.addRole(roleVo);
        return ResponseEntity.SUCCESS("添加角色成功", null);
    }

    @GetMapping("/delRole/{id}")
    @PreAuthorize("hasAnyAuthority('role:del')")
    public ResponseEntity delRole(@PathVariable @NotNull int id) {
        roleService.delLogic(id);
        return ResponseEntity.SUCCESS("删除角色成功", null);
    }

    @PostMapping("/updateRole")
    @PreAuthorize("hasAnyAuthority('role:edit')")
    public ResponseEntity updateRole(@RequestBody RoleVo roleVo) {
        log.debug("roleVo：{}", roleVo);
        roleService.updateRole(roleVo);
        return ResponseEntity.SUCCESS("修改角色成功", null);
    }

    @GetMapping("/roleList/{current}")
    @PreAuthorize("hasAnyAuthority('role:list')")
    public ResponseEntity roleList(@PathVariable int current) {
        log.debug("auth{}", SecurityContextHolder.getContext().getAuthentication());
        if (current == 0) {
            Page<Role> rolePage = roleService.roleList(1);
            return ResponseEntity.SUCCESS("查找角色列表成功", rolePage);
        } else {
            Page<Role> rolePage = roleService.roleList(current);
            return ResponseEntity.SUCCESS("查找角色列表成功", rolePage);
        }
    }

    @GetMapping("/del/{id}")
    @PreAuthorize("hasAnyAuthority('role:del')")
    public ResponseEntity del(@PathVariable int id) {
        roleService.delRole(id);
        return ResponseEntity.SUCCESS("删除角色成功", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 查询所有的角色（不分页）
     * @Date 14:58 2022/8/31
     * @Author 魏才林
     * @Param []
     **/
    @GetMapping("/list")
    public ResponseEntity list() {
        return ResponseEntity.SUCCESS("查询所有角色成功", roleService.list());
    }
}
